package com.daffodil.storage.client.sftp;

import java.util.Properties;

import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import cn.hutool.core.util.ObjectUtil;

/**
 * 
 * @author yweijian
 * @date 2023年11月3日
 * @version 1.0
 * @description
 */
public class SessionPooledFactory extends BasePooledObjectFactory<Session> {

    private String host;

    private Integer port;

    private String username;

    private String password;

    private int soTimeout;

    @Override
    public Session create() throws Exception {
        JSch jsch = new JSch();
        Session session = jsch.getSession(username, host, port);
        if(ObjectUtil.isNotEmpty(password)) {
            session.setPassword(password);
        }
        if(ObjectUtil.isNull(soTimeout)) {
            soTimeout = 3000;
        }
        session.setTimeout(soTimeout);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        return session;
    }

    @Override
    public PooledObject<Session> wrap(Session session) {
        return new DefaultPooledObject<Session>(session);
    }

    @Override
    public void destroyObject(PooledObject<Session> p) throws Exception {
        p.getObject().disconnect();
    }

    @Override
    public boolean validateObject(PooledObject<Session> p) {
        return p.getObject().isConnected();
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getSoTimeout() {
        return soTimeout;
    }

    public void setSoTimeout(int soTimeout) {
        this.soTimeout = soTimeout;
    }

}
